package com.freewater.javabase.demo.designpattern.command2.macro.invoker;

import com.freewater.javabase.demo.designpattern.command2.macro.command.Command;
import com.freewater.javabase.demo.designpattern.command2.macro.command.NoCommand;

/**
 * 调用者（Invoker）。接受命令对象，然后调用命令对象的接口方法委托命令对象执行实际的调用过程
 * Created by FreeWater on 2017/4/4.
 */
public class RemoteControllerWithUndo {
	private Command[] onCommands = new Command[7];// 持有命令对象的引用
	private Command[] offCommands = new Command[7];// 持有命令对象的引用

	private Command undoCommand; // 记录最后一次被操作的命令对象

	public RemoteControllerWithUndo(){
		NoCommand noCommand = new NoCommand();
		for(int i = 0; i < onCommands.length; i++){
			onCommands[i] = noCommand;
			offCommands[i] = noCommand;
		}
		undoCommand = noCommand;
	}

	public void setCommand(int slot, Command onCommand, Command offCommand){// 可以运行时改变命令对象
		onCommands[slot] = onCommand;
		offCommands[slot] = offCommand;
	}

	public void onButtonWasPressed(int slot){// 调用命令对象方法让命令对象去调用接收者/执行者完成具体的功能
		onCommands[slot].execute();
		undoCommand = onCommands[slot];
	}

	public void offButtonWasPressed(int slot){// 调用命令对象方法让命令对象去调用接收者/执行者完成具体的功能
		offCommands[slot].execute();
		undoCommand = offCommands[slot];
	}

	public void undoButtonWasPressed(){
		undoCommand.undo();
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < onCommands.length; i++){
			sb.append("[slot " + i + "]" +  onCommands[i].getClass().getName() + "\t" + offCommands[i].getClass().getName() + "\n");
		}
		return sb.toString();
	}
}
